package rmmk.algorithms.features.fatures;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import rmmk.algorithms.features.abstraction.AbstractFeatureExtractor;
import rmmk.algorithms.features.global.PairsOfWordsGlobal;
import rmmk.framework.datasources.Document;

/**
 * W tym ekstraktorze wybieramy n najczęściej występujących par słów,
 * następnie w wektorze umieszczamy liczbę zliczonych par w danym dokumencie
 * @author Marcin
 *
 */
public class PairsOfWordsExtractor extends AbstractFeatureExtractor{
	Logger logger = LoggerFactory.getLogger(PairsOfWordsExtractor.class);
	private int featureSize = 0;
	
	public PairsOfWordsExtractor(int featureSize) {
		this.featureSize = featureSize;
	}
	
	@Override
	public Double[] doCalculate(Document document) {
		Double[] vector = new Double[featureSize];
		
		Map<String, Integer> globalMap = PairsOfWordsGlobal.getNBiggest(featureSize);
		Map<String, Integer> localMap = new HashMap<String, Integer>();
		
		if(globalMap.size() == 0)
			logger.warn("Brak zliczonych par słów. Tak nie można, to nie zadziała.");
		
		for(int i = 0; i < document.getExtractedWords().size() -1; ++i){
			if(checkIfPair(document.getExtractedWords().get(i), 
					document.getExtractedWords().get(i+1), globalMap))
			{
				addToMap(i, globalMap, localMap, document);
			}
		}
		
		String[] keyArray = globalMap.keySet().toArray(new String[globalMap.keySet().size()]);
		
		for(int i = 0; i < vector.length; ++i)
		{
			int count = localMap.containsKey(keyArray[i]) ? localMap.get(keyArray[i]) : 0;
			
			vector[i] = (double) count;
		}
		
		return vector;
	}
	
	private void addToMap(int i, Map<String, Integer> from, Map<String, Integer> to, Document document){
		String a = document.getExtractedWords().get(i);
		String b = document.getExtractedWords().get(i+1);
		
		String c = null;
		if(from.containsKey(a+b))
			c=a+b;
		else c=b+a;
		
		Integer count = 0;
		
		if(to.containsKey(c))
			count = to.get(c) + 1;
		
		to.put(c, count);
	}
	
	private boolean checkIfPair(String a, String b, Map<String, Integer> globalMap)
	{
		if(globalMap.containsKey(a+b) || globalMap.containsKey(b+a))
			return true;
		else return false;
	}

	@Override
	public int getFeatureSize() {
		return featureSize;
	}

}
